﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace YArchitech.Plumbing
{
	public class InnerUtil
	{
		public static List<ElementId> getDataInProject(Autodesk.Revit.DB.Document _doc, Guid guid, string name, bool isClean)
		{
			SchemaBuilder schemaBuilder = new SchemaBuilder(guid);
			schemaBuilder.SetReadAccessLevel((AccessLevel)1);
			schemaBuilder.SetWriteAccessLevel((AccessLevel)1);
			schemaBuilder.SetVendorId("ADSK");
			schemaBuilder.SetSchemaName(name);
			schemaBuilder.AddSimpleField(name, typeof(string));
			Schema schema = schemaBuilder.Finish();
			Schema schema2 = (from x in Schema.ListSchemas()
			where x.SchemaName == name
			select x).FirstOrDefault<Schema>();
			Entity entity = _doc.ActiveView.GetEntity(schema);
			string text = "";
			try
			{
				text = entity.Get<string>(schema2.GetField(name));
			}
			catch (Exception)
			{
			}
			List<ElementId> list = new List<ElementId>();
			if (string.IsNullOrEmpty(text))
			{
				return list;
			}
			foreach (string text2 in text.Split(new char[]
			{
				','
			}))
			{
				if (text2 != null && text2 != "")
				{
					list.Add(new ElementId(Convert.ToInt32(text2)));
				}
			}
			if (isClean)
			{
				InnerUtil.StoreDataInProject(_doc, guid, name, new List<ElementId>(), isClean);
			}
			return list;
		}

		public static void StoreDataInProject(Autodesk.Revit.DB.Document _doc, Guid guid, string name, List<ElementId> eles, bool isClean)
		{
			SchemaBuilder schemaBuilder = new SchemaBuilder(guid);
			schemaBuilder.SetReadAccessLevel((AccessLevel)1);
			schemaBuilder.SetWriteAccessLevel((AccessLevel)1);
			schemaBuilder.SetVendorId("ADSK");
			schemaBuilder.SetSchemaName(name);
			schemaBuilder.AddSimpleField(name, typeof(string));
			Schema schema = schemaBuilder.Finish();
			Entity entity = new Entity(schema);
			Field field = schema.GetField(name);
			string text = "";
			if (!isClean)
			{
				foreach (ElementId elementId in InnerUtil.getDataInProject(_doc, guid, name, false))
				{
					text = text + elementId.ToString() + ",";
				}
				using (List<ElementId>.Enumerator enumerator = eles.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						ElementId arg = enumerator.Current;
						text = text + arg + ",";
					}
					goto IL_DE;
				}
			}
			eles.Clear();
			IL_DE:
			entity.Set<string>(field, text);
			_doc.ActiveView.SetEntity(entity);
		}
	}
}
